var util = require('./utils/util.js');
var api = require('./config/api.js');
var user = require('./services/user.js');
var version = require('./config/version.js');

App({
  onLaunch: function(opt) {
    var pages = getCurrentPages();
    if (pages.length == 0) {
      //隐藏系统tabbar
      wx.hideTabBar();
      var info;
      let t = this;
      wx.getSystemInfo({
        success: function(res) {
          info = res;
          t.globalData.systemInfo = res;
          t.statusBarHeight = res.statusBarHeight;
          if (res.statusBarHeight == 44) {
            t.globalData.isIphoneX = true
          }

          if (res.platform == "ios") {
            t.globalData.platform = "ios"
          }
          if (res.platform == "android") {
            t.globalData.platform = "android"
          }

        }
      })

      if (opt && opt.scene && opt.scene == 1044) { //1044转发场景值
        if (info.SDKVersion >= '2.0.9') {
          console.log(info.SDKVersion)
          wx.getShareInfo({
            shareTicket: opt.shareTicket,
            success: function(res) {
              var encryptedData = res.encryptedData;
              var iv = res.iv;
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'
          })
        }
      }
      var that = this;
      this.globalData.checkLogin = false
      this.globalData.userInfo = wx.getStorageSync('userInfo');
      this.globalData.token = wx.getStorageSync('token');
      this.globalData.hasPhone = wx.getStorageSync('hasPhone');
      if (this.globalData.userInfo) {
        this.globalData.hasUserInfo = true
        this.globalData.auth = true
        // 解决因为usrinfo结构变化导致的数据不一直问题
        let uf = this.globalData.userInfo;
        if (uf.hasOwnProperty("uuid")) {
          wx.clearStorageSync()
        }
      }

      wx.getSetting({
        success: (ress) => {
          var that = this
          if (ress.authSetting) {
            if (ress.authSetting["scope.userInfo"]) {
              that.globalData.auth = true
              // 重新获取用户信息
              let code = null;
              return that.login().then((res) => { //userInfo
                code = res.code;
                wx.getUserInfo({
                  withCredentials: true,
                  success: function(res_user) {
                    //先去登陆        
                    wx.request({
                      url: api.userAuth,
                      data: {
                        platform: 'wx',
                        authorizationCode: code,
                        userEncryptrfData: res_user.encryptedData,
                        iv: res_user.iv
                      },
                      method: 'POST',
                      header: {
                        'Content-Type': 'application/json',
                        'accessToken': wx.getStorageSync('token'),
                        'appVersion': version.appVersion,
                        'deviceModel': that.globalData.systemInfo.model,
                        'platform': 'wx',
                        'build': version.build,
                        'deviceMachineCode': '',
                        'deviceOS': that.globalData.systemInfo.system.split(" ")[0],
                        'deviceOSVersion': that.globalData.systemInfo.system
                      },
                      success: function(res) {
                        if (res && res.statusCode == 200 && res.data.code == 200) {
                          wx.setStorageSync('token', res.data.data.token);
                          that.globalData.token = res.data.data.token;
                          var userInfo = res.data.data.user
                          if (userInfo && !userInfo.avatarUrl) {
                            userInfo.avatarUrl = version.defaultAvataUrl
                          }
                          var uuid = userInfo.id;
                          wx.setStorageSync('userInfo', userInfo);
                          that.globalData.userInfo = userInfo
                          that.globalData.hasUserInfo = true
                          that.globalData.hasPhone = true
                          that.globalData.auth = true
                          wx.setStorageSync('auth', true);
                          wx.setStorageSync('hasPhone', true);
                        }
                        if (res && res.data.code == 301) {
                          wx.setStorageSync('token', res.data.data.token);
                          that.globalData.token = res.data.data.token;
                          that.globalData.hasPhone = false
                          wx.setStorageSync('hasPhone', false);
                        }
                        that.globalData.checkLogin = true;
                        //由于这里是网络请求，可能会在 Page.onLoad 之后才返回
                        // 所以此处加入 callback 以防止这种情况
                        if (that.checkLoginReadyCallback) {
                          that.checkLoginReadyCallback(res);
                        }
                      }
                    })
                  }
                })
              })
              // 重新获取用户信息
            } else {
              that.globalData.checkLogin = true;
              if (that.checkLoginReadyCallback) {
                that.checkLoginReadyCallback(1);
              }
            }

          }
        }
      })

    } //pages.length == 0
  },



  statusBarHeight: 0,

  editTabbar: function() {
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },



  globalData: {
    systemInfo: null,
    userInfo: {}, //用户信息
    hasUserInfo: false, //用户是否有信息的标志
    hasPhone: false, //用户是否绑定过手机号
    auth: false, //授权与否
    token: '', //登陆与否
    isIphoneX: false, //是否是iphoneX
    tabBar: {
      "backgroundColor": "#ffffff",
      "color": "#979795",
      "selectedColor": "#1c1c1b",
      "list": [{
          "pagePath": "/pages/index/index",
          "iconPath": "icons/home.png",
          "selectedIconPath": "icons/home_se.png",
          // "text": "首页"
        },
        {
          "pagePath": "/pages/follow/follow",
          "iconPath": "icons/fav.png",
          "selectedIconPath": "icons/fav_se.png",
          // "text": "关注"
        },
        {
          "pagePath": "/pages/me/me",
          "iconPath": "icons/user.png",
          "selectedIconPath": "icons/user_se.png",
          // "text": "我的"
        }
      ]
    }
  },
  get: function(url) {
    var promise = new Promise((resolve, reject) => {
      var that = this;
      wx.request({
        url: url,
        method: 'GET',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) { //服务器返回数据
          if (res.data.success) { //res.data 为 后台返回数据，格式为{"data":{...}, "info":"成功", "status":1}
            resolve(res.data.data);
          } else { //返回错误提示信息
            reject(res.data.info);
          }
        },
        error: function(e) {
          reject('网络出错');
        }
      })
    });
    return promise;
  },
  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },


})